﻿using System;
using System.Collections.Generic;
using System.Linq;
using ZyGame.Execute;
using Newtonsoft.Json;
using ZyGame.Transport;

namespace ZyGame.Resource
{
    public class UpdateResourceRunnable : Runnable, IDisposable
    {
        private MultiFileDownload runnable;

        public static UpdateResourceRunnable Create(params PackageInfo[] packages)
        {
            string name = "[UPDATE RESOURCES LIST]" + string.Join("", packages.Select(x => x.name));
            if (Client.Running.TryGetOrCreate(name, out UpdateResourceRunnable updateResourceRunnable))
            {
                return updateResourceRunnable;
            }

            updateResourceRunnable.runnable = MultiFileDownload.Create(packages);
            updateResourceRunnable.Execute(updateResourceRunnable.runnable.Waitting);
            updateResourceRunnable.Execute(updateResourceRunnable.RefreshLocalFileList);
            return updateResourceRunnable;
        }

        public Runnable ListenerProgres(Action<float> callback)
        {
            runnable.ListenerProgres(callback);
            return this;
        }

        public override bool EnsureExecutedSuccessful()
        {
            return runnable.EnsureExecutedSuccessful();
        }

        private void RefreshLocalFileList()
        {
            List<PackageInfo> packages = runnable.result.Select(x => x.package).ToList();
            Dictionary<string, List<PackageInfo>> splitModules = new Dictionary<string, List<PackageInfo>>();
            foreach (PackageInfo package in packages)
            {
                if (!splitModules.TryGetValue(package.module, out List<PackageInfo> list))
                {
                    splitModules.Add(package.module, list = new List<PackageInfo>());
                }

                list.Add(package);
            }

            foreach (var module in splitModules)
            {
                string cfg = JsonConvert.SerializeObject(module.Value);
                Client.File.WriterData(AppConfig.GetModuleFileListName(module.Key), cfg.GetBytes());
                Client.Console.WriteLine($"更新{AppConfig.GetModuleFileListName(module.Key)}文件列表" + cfg);
            }
        }
    }
}